<template>
  <div class="app-container addParam-wrap">
    <el-row class='select-row'>
      <el-col :span='24'>
        <p class='title'>{{$t('ota.upgrade.first')}}</p>
        <el-form :model='form' label-width="100px" ref='selectForm' label-position="top" inline class='selectForm' :rules='formRules'>
          <el-form-item :label="$t('ota.upgrade.deviceTypeName')" prop="deviceTypeId">
            <el-select v-model="form.deviceTypeId" @change="deviceTypeChange"
                       learable size="middle" style="width: 240px">
              <el-option v-for="dict in typeOptions"
                         :key="dict.value" :label="dict.label" :value="dict.value" />
            </el-select>
          </el-form-item>
          <el-form-item :label="$t('ota.upgrade.deviceModelName')" prop="deviceModelId">
            <el-select @change='handleModelChange' v-model="form.deviceModelId" clearable size="middle" style="width: 240px">
              <el-option v-for="dict in modelOptions"
                         :key="dict.value" :label="dict.label" :value="dict.value" />
            </el-select>
          </el-form-item>
          <el-form-item  :label="$t('ota.version.versionType')" prop="versionType">
              <el-select @change='handleVersionTypeChange' style="width: 240px" v-model="form.versionType" :placeholder="$t('ota.version.placeholder.versionType')" :style="{ width: '100%' }">
                  <el-option v-for="dict in dict.type.firmware_type" :key="dict.value" :label="dict.label"
                      :value="dict.value" />
              </el-select>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
    <el-row class='select2-row'>
      <el-col :span='12' class='mr20'>
        <div class='title flex'>
          <span>{{$t('ota.upgrade.two')}}</span>
          <span class='link-type'>{{$t('ota.upgrade.selectedDevice')}}：{{deviceList.length}}</span>
          <el-button v-if='deviceList.length' type="text" plain icon="el-icon-edit" size="mini" @click="showDeviceDialog = true"
                     v-hasPermi="['system:device:import']">
            {{$t('common.button.edit')}}
          </el-button>
        </div>
        <div :class="!deviceList.length?'second-wrap':'second-wrap2'">
          <i v-if='!deviceList.length' class='el-icon-plus' @click='handleAddDevice'></i>
          <el-table border v-else :data="deviceList" :empty-text="$t('common.table.noData')">
            <el-table-column :show-overflow-tooltip="true" align="center" prop="deviceCode" :label="$t('ota.upgrade.deviceCode')" width="150" />
            <el-table-column :show-overflow-tooltip="true" align="center" prop="softwareVersion" :label="$t('ota.upgrade.softwareVersion')" width="200" />
            <el-table-column :show-overflow-tooltip="true" align="center" prop="deviceTypeName" :label="$t('ota.upgrade.deviceTypeName')" />
            <el-table-column :show-overflow-tooltip="true" align="center" prop="deviceModelName" :label="$t('ota.upgrade.deviceModelName')" />
            <el-table-column :show-overflow-tooltip="true" align="center" prop="userCode" :label="$t('ota.upgrade.userCode')" width="150"  />
            <el-table-column :show-overflow-tooltip="true" align="center" prop="vehicleNick" :label="$t('ota.upgrade.vehicleNick')" width="150"  />
          </el-table>
        </div>
      </el-col>

      <el-col :span='12'>
        <div class='title flex'>
          <span>{{$t('ota.upgrade.third')}}</span>
          <span class='link-type'>{{$t('ota.upgrade.selectedVersion')}}：{{versionNum}}</span>
          <div class='pack-div'>
            <div class="pack-div">
              <span for="" class='w80'>{{$t('ota.upgrade.versionNum')}}:</span>
              <el-input v-model='queryParams.versionNo' size='mini'></el-input>
            </div>
            <el-button class='ml0' size='mini' type='primary' @click='handleQueryVersion' plain icon="el-icon-search">{{$t('common.button.search')}}
            </el-button>
          </div>
        </div>
        <el-table border :data="versionList" v-loading='verLoading' :height="total > 0 ? 'calc(100% - 100px)' :'calc(100% - 60px)'" :empty-text="$t('common.table.noData')">
          <el-table-column width="55" label="" align="center">
            <template slot-scope='scope'>
              <el-radio v-model="selectRow" :label="scope.$index" @change.native='getCheckedRow(scope.row)'>&nbsp;</el-radio>
            </template>
          </el-table-column>
          <el-table-column :show-overflow-tooltip="true" property="versionNo" :label="$t('ota.upgrade.versionNum')" width="210"></el-table-column>
          <!-- <el-table-column :show-overflow-tooltip="true" property="versionRelyNo" :label="$t('ota.upgrade.dependVersion')" width="160"></el-table-column> -->
          <el-table-column :show-overflow-tooltip="true" property="deviceModelName" :label="$t('ota.upgrade.suitDeviceModel') " width="190"></el-table-column>
          <el-table-column :show-overflow-tooltip="true" property="originalFileName" :label="$t('ota.version.originalFileName') " width="190"></el-table-column>
          <el-table-column :show-overflow-tooltip="true" property="versionUrl" :label="$t('ota.upgrade.fileAddress')" width="220"></el-table-column>
          <el-table-column :show-overflow-tooltip="true" property="versionState" :label="$t('ota.upgrade.useState')" width="140">
            <template slot-scope="scope"><span>
              {{scope.row.versionState === 1 ? $t('ota.upgrade.enable') : $t('ota.upgrade.disable')}}
            </span></template>
          </el-table-column>
          <el-table-column :show-overflow-tooltip="true" property="versionTypeName" :formatter="versionTypeFormat" :label="$t('ota.upgrade.versionType')" width="120">
          </el-table-column>
        </el-table>
        <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="handleQueryVersion"/>

      </el-col>
    </el-row>
    <el-row class='select-row mt20'>
      
        <p class='title'>{{$t('ota.upgrade.four')}}</p>
        <el-form :model='form' label-width="140px" inline label-position="top" ref='upForm' class='four-wrap' :rules="formRules">
            <el-form-item :label="$t('ota.upgrade.upStartTime')" prop="upgradeTimes" >
              <el-date-picker :picker-options="expireTimeOption" v-model="form.upgradeTimes"
                              type="datetime" placeholder=""
                              default-time="12:00:00" :clearable ="false">
              </el-date-picker>
            </el-form-item>
            <el-form-item :label="$t('ota.upgrade.upExpiresTime')" prop="overtimeTimes">
              <el-date-picker :picker-options="expireTimeOption" v-model="form.overtimeTimes" type="datetime" placeholder=""
                              default-time="12:00:00" :clearable ="false">
              </el-date-picker>
            </el-form-item>
            <el-form-item :label="$t('ota.upgrade.taskName')" prop="planName">
              <el-input v-model='form.planName' style='width:220px'></el-input>
            </el-form-item>
            <el-form-item :label="$t('ota.upgrade.installationMode')" prop="installMode" style="flex:1">
              <el-select  style="width: 240px" v-model="form.installMode" :placeholder="$t('ota.upgrade.placeholder.installationMode')" >
                  <el-option v-for="dict in dict.type.installation_mode" :key="dict.value" :label="dict.label"
                        :value="dict.value" />
              </el-select>          
            </el-form-item>
            <el-form-item :label="$t('ota.upgrade.taskDesc')" prop="comment" style="flex:1">
              <el-input v-model='form.comment' type='textarea' autosize maxlength="128" show-word-limit></el-input>
            </el-form-item>
           

        </el-form>
    </el-row>
    <div class='add-footer'>
      <el-button :disabled='disabled' type='primary' @click='handleUpgrade'>{{$t('ota.upgrade.upgrade')}}</el-button>
    </div>

    <div>
      <el-dialog :title="this.$t('ota.upgrade.deviceFailList')" :visible.sync="errorVisiable"  append-to-body @close="cancel">
        <el-table :data="errorList" height="500px" style="width: 100%; background-color: #fff;">
          <el-table-column show-overflow-tooltip align="center" prop="deviceCode" :label="$t('ota.upgrade.deviceCode')"></el-table-column>
          <el-table-column show-overflow-tooltip align="center" prop="errorMsg" :label="$t('ota.upgrade.errorMsg')"></el-table-column>
        </el-table>
        <div slot="footer" style="text-align:center">
          <el-button type='primary' size="mini" @click="handleConfirm" v-hasPermi="['device:upgrade:submit']">{{ $t('common.button.confirm') }}</el-button>
        </div>
      </el-dialog>
    </div>

    <DeviceDialog :params='dialogParams' :deviceList='deviceList' :dialogVisible.sync='showDeviceDialog' @selection='handleSelection'
                  @close='handleDeviceDialogClose' />
  </div>
</template>

<script>
import DeviceDialog from './modules/DeviceDialog';
import { filterListBin } from '@/api/version/data'
import { insertUpgrade } from '@/api/ota/upgrade'
import { typeTree } from "@/api/device/type";
import { modelTree } from "@/api/device/model";

export default {
  name: 'DeviceUpgrade',
  components: {
    DeviceDialog
  },
  dicts: ['firmware_type','installation_mode'],
  data() {
    return {
      typeOptions: [],
      modelOptions: [],
      errorList:[],
      errorVisiable:false,
      form: {
        deviceTypeId: undefined,
        deviceModelId: undefined,
        upgradeTime: undefined,
        overtimeTime: undefined,
        installMode:undefined,
        comment: undefined,
        planName: undefined,
        versionId: undefined,
        versionType:undefined,
        deviceList: [],
        versionUrl:undefined,
        overtimeTimes:undefined,
        upgradeTimes:undefined,
      },
      formRules: {
        deviceTypeId: [
          {required: true, message: this.$t('ota.upgrade.rules.deviceTypeId'), trigger: 'change'}
        ],
        deviceModelId: [
          {required: true, message: this.$t('ota.upgrade.rules.deviceModelId'), trigger: 'change'}
        ],
        upgradeTimes: [
          {required: true, message: this.$t('ota.upgrade.rules.upgradeTimes'), trigger: 'blur'}
        ],
        overtimeTimes: [
          {required: true, message: this.$t('ota.upgrade.rules.overtimeTimes'), trigger: 'blur'}
        ],
        planName: [
          {required: true, message: this.$t('ota.upgrade.rules.planName'), trigger: 'blur'}
        ]
      },
      expireTimeOption: {
        disabledDate(date) {
          //disabledDate 文档上：设置禁用状态，参数为当前日期，要求返回 Boolean
          return date.getTime() < Date.now() - 24 * 60 * 60 * 1000;
        }
      },
      versionNo: undefined,
      versionType:undefined,
      statusOptions: [],
      versionList: [],
      showDeviceDialog: false,
      showImportDialog: false,
      verLoading: false,
      deviceList: [],
      selectRow: '',
      versionNum: '',
      total: 0,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        versionNo: undefined,
        deviceTypeId: undefined,
        deviceModelId: undefined,
        versionType:undefined
      },
    }
  },
  computed: {
    disabled() {
      let flag = false;
      let list = ['deviceTypeId', 'deviceModelId', 'versionId', 'deviceList', 'upgradeTimes', 'overtimeTimes', 'planName'];
      list.forEach(item => {
        if (!this.form[item]) {
          flag = true
        }
      })
      return flag;
    },
    dialogParams() {
      return { deviceTypeId: this.form.deviceTypeId, deviceModelId: this.form.deviceModelId, bluetoothUpgrade: false }
    }
  },
  created() {
    this.getTypes();
  },
  methods: {
    deviceTypeChange(typeId) {
      if (typeId) {
        this.getModels(typeId)
      } else {
        this.form.deviceModelId = undefined
        this.modelOptions = []
      }
    },
    getTypes() {
      typeTree().then(response => {
        this.typeOptions = response.data;
      });
    },
    getModels(typeId) {
      modelTree(typeId).then(response => {
        this.modelOptions = response.data;
      });
    },
    versionTypeFormat(row, column) {
      return this.selectDictLabel(this.dict.type.firmware_type, row.versionType);
    },
    handleDeviceDialogClose() {
      this.showDeviceDialog = false;
    },
    handleModelChange(val) {
      // if (val && this.form.deviceTypeId) {
      //   this.handleQueryVersion()
      // }
    },
    handleVersionTypeChange(){
      this.handleQueryVersion()
    },
    handleAddDevice() {
      if (this.form.deviceTypeId && this.form.deviceModelId) {
        this.showDeviceDialog = true;
        this.handleQueryVersion();
      } else {
        this.$alert(this.$t('ota.upgrade.typeFirst'), this.$t('common.prompt.tip'), {
          confirmButtonText: this.$t('common.button.confirm'),
          callback: action => {}
        });
      }
    },
    handleUpgrade() {
      this.form.overtimeTimes = this.form.overtimeTimes.getTime();
      this.form.upgradeTimes = this.form.upgradeTimes.getTime();

      if (this.form.upgradeTimes > this.form.overtimeTimes) {
        this.$modal.msgWarning(this.$t('ota.upgrade.issueTimeError'));
        return
      }

      insertUpgrade(this.form).then(res => {
        if (res.code === 200) {
          this.$modal.addSuccess();
          // 跳转列表
          const obj = { path: "/ota/upgradeTask" };
          this.$tab.closeOpenPage(obj);
        }
      }).catch(err => {
        this.$message.error(err.msg);
      })
    },
    handleSelection(list) {
      this.deviceList = list;
      this.form.deviceList = list.map(item => {
        return item.deviceCode
      });
    },
    handleQueryVersion() {
      this.verLoading = true;
      this.deviceTypeId = this.form.deviceTypeId
      this.deviceModelId = this.form.deviceModelId
      this.queryParams.versionType = this.form.versionType;
      filterListBin(this.queryParams).then(res => {
        this.versionList = res.rows;
        this.total = res.total;
        this.verLoading = false;
      })
    },

    getCheckedRow(row) {
      this.form.versionId = row.versionId;
      this.form.versionUrl = row.versionUrl;
      this.versionNum = row.versionNo;
    },

    //弹窗确定按钮
    handleConfirm(){
      this.errorVisiable = false;
      //1秒后刷新当前界面
      setTimeout(() => {
        location.reload();
      }, 1000);
    },

    cancel(){
      this.errorVisiable = false;
      //0.5秒后刷新当前界面
      setTimeout(() => {
        location.reload();
      }, 500);
    }
  }
}
</script>

<style lang="scss" scoped>
.addParam-wrap {
  background-color: #f0f2f5;
}
.title {
  border-bottom: 1px solid #ccc;
  margin: 0 0 10px 0;
  padding-bottom: 10px;
  text-align: left;
  font-size: 14px;
}
.select-row {
  background: #fff;
  padding: 20px;
  margin-bottom: 30px;
}
.select2-row {
  margin: 0;
  display: flex;
  justify-content: space-between;
  .el-col-12 {
    background: #fff;
    padding: 20px;
    height: 52vh;
  }
}
.second-wrap {
  height: calc(100% - 60px);
  display: flex;
  justify-content: center;
  align-items: center;
  .el-icon-plus {
    font-size: 32px;
    cursor: pointer;
  }
}
.second-wrap2 {
  height: calc(100% - 60px);
  overflow: auto;
}
.el-form-item {
  width: 300px;
}
.add-footer {
  display: flex;
  justify-content: flex-end;
  padding: 5px 0;
}
.flex {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.pack-div {
  display: flex;
  align-items: center;
}
.w80 {
  min-width: 80px;
}
.four-wrap {
  display: flex;
}
</style>
